package cn.itsource.controller.html;

import cn.itsource.domain.BlogArticle;
import cn.itsource.domain.html.ArticleGdDto;
import cn.itsource.mapper.ArticleMapper;
import cn.itsource.query.BlogArticleQuery;
import cn.itsource.service.BlogArticleService;
import cn.itsource.util.AjaxResult;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController //@Contorller和@ResponseBody（所有的方法都返回json格式）
@RequestMapping("/html/blogArticle") //公共路径
public class HtmlArticleController {
    @Autowired
    private BlogArticleService blogArticleService;
    @Autowired
    private ArticleMapper mapper;
    @PostMapping("/pageBlogList")
    public AjaxResult pageBlogList(@RequestBody BlogArticleQuery query){
        //设置分页信息
        PageHelper.startPage(query.getPage(), query.getRows());

        //查询
        List<BlogArticle> resultList = mapper.selectMyPageList(query);

        //返回结果集（使用PageInfo对象进行封装）
        return AjaxResult.Success(new PageInfo<>(resultList));
    }
    /**
     * 归档页面-查询所有博客数据
     */
    @GetMapping("/getBlogGdList/{time}")
    public AjaxResult getBlogGdList(@PathVariable("time") String time)
    {
        //如果等于-1表示查询所有，否则按照对应的年月查询文章信息
        time = "all".equalsIgnoreCase(time) ? "" : time;
        List<BlogArticle> list = mapper.getBlogGdList(time);
        //根据年份进行分组
        Map<String, List<BlogArticle>> resultMap = list.stream().collect(Collectors.groupingBy(BlogArticle::getYear));
        List<ArticleGdDto> gdList = new ArrayList<>();
        ArticleGdDto gd = null;
        //遍历resultMap，封装结果进行返回
        for(Map.Entry<String, List<BlogArticle>> entry : resultMap.entrySet()){
            gd = new ArticleGdDto();
            gd.setYear(entry.getKey());
            gd.setArticleList(entry.getValue());
            gdList.add(gd);
        }
        return AjaxResult.Success(gdList);
    }
    @GetMapping("/{articleId}")
    public AjaxResult getBlogGdList(@PathVariable("articleId") Long id){
        BlogArticle one = blogArticleService.findOne(id);
        return AjaxResult.Success(one);
    }
    @GetMapping("/getDependentArticles/{articleId}")
    public AjaxResult getBlogArticle(@PathVariable("articleId")  Long id){
        List<BlogArticle> type = mapper.findType(id);
        return AjaxResult.Success(type);
    }
    @GetMapping("/getArticleListByTypeId/{articleId}")
    public AjaxResult getArticleListByTypeId(@PathVariable("articleId")  Long id){
        List<BlogArticle> type = mapper.findType(id);
        return AjaxResult.Success(type);
    }
    @GetMapping("/selectArticleTimeStatistics")
    public AjaxResult selectArticleTimeStatistics(){
        List<BlogArticle> all = blogArticleService.findAll();
        return AjaxResult.Success(all);
    }
//    添加取消时-删除oss中已存入的图片
    @DeleteMapping("/deleteOss/{fileName}")
    public AjaxResult delete(@PathVariable("fileName") String fileName ){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tFdPf6sUHbb3V4gHa8V";
        String accessKeySecret = "7WuXzHvpmFEM3q7Ez9E49xmNn2dV5w";
// 填写Bucket名称，例如examplebucket。
        String bucketName = "lg-java";

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, fileName);
        } catch (OSSException oe) {
            System.out.println("Error Message:" + oe.getErrorMessage());
        } catch (ClientException ce) {
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        System.err.println("执行完毕");
        return AjaxResult.Success();
    }


}
